package org.lightmtv.response;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.lightcommons.template.Template;
import org.lightcommons.util.Assert;
import org.lightcommons.web.MimeType;
import org.lightcommons.web.auth.AuthManager;
import org.lightmtv.LightMtvException;
import org.lightmtv.config.GlobalContext;
import org.lightmtv.util.CookieMap;
import org.lightmtv.util.SessionMap;

/**
 * 
 * @author GL
 * @since 0.1.1
 */
public class TemplateResponse extends TextResponse{

	private Template template;
	@SuppressWarnings("unchecked")
	private Map context;
	
	public TemplateResponse(Template template,String contextType) {
		init(template, contextType);
	}

	@SuppressWarnings("unchecked")
	private void init(Template template,String contextType){
		Assert.notNull(template,"Can't initlize TemplateResponse. Cause of template is null.");
		this.template = template;
		this.context = new HashMap();
		context.put("req", GlobalContext.getRequest());
		context.put("auth", AuthManager.getAuthentication());
		context.put("loginUser", AuthManager.getUser());
		context.put("global", GlobalContext.getVars());
		context.put("session", new SessionMap(GlobalContext.getSession()));
		context.put("cookie", new CookieMap(GlobalContext.getRequest().getCookies()));
		context.put("locale", GlobalContext.getLocale());
		//TODO: encoding,locale,config
		setContentType(contextType);
	}
	
	public TemplateResponse(String path,String encoding,String contextType) {
		try {
			Locale locale = GlobalContext.getLocale();
			Template template = GlobalContext.getSettings().getTemplateFactory().getTemplate(path, locale, encoding); 
			init( template ,contextType);
		} catch (Exception e) {
			throw new LightMtvException("can not init template of:"+path,e);
		}
	}
	
	public TemplateResponse(String path) {
		this(path,"utf-8",MimeType.HTML.toString());
	}
	
	@SuppressWarnings("unchecked")
	public TemplateResponse put(String key,Object value){
		context.put(key, value);
		return this;
	}
	
	@SuppressWarnings("unchecked")
	public TemplateResponse putAll(Map map){
		context.putAll(map);
		return this;
	}
	
	@Override
	public CharSequence getText() {
		return template.render(context,GlobalContext.getLocale());
	}
}
